// todo 封装渲染数据
const query = {
  advimgdesc: '', // 广告图描述
  advimgpos: '', // 广告图所在广告位id
  page: 1,  //页码
  limit: 10 // 每页数量
}


async function getimgList() {

  const { data: { data } } = await axios.get('/ydd_advimg/list', { params: query })
  // console.log(data)

  document.querySelector('#list').innerHTML = data.data.map((item) => {
    const { id, advimgdesc, advimglink, advimgpos, advimgsrc, advposname, default_data } = item
    return `
        <tr>
            <td><input type="checkbox" name="" class="j-checkbox" style="cursor: pointer;"></td>
            <td>${id}</td>
            <td>${advposname}</td>
            <td>${advimgdesc}</td>
            <td><img src="http://124.223.14.236:8060/${advimgsrc}" alt=""></td>
            <td>${advimglink}</td>
            <td class="caozuo">
              <button type="button" class="layui-btn layui-btn-xs btn_editImg"
                style="width: 30px; border-radius: 50%;  padding: 0 8px; background-color: #1e9fff;" data-id="${id}">
                <i class="layui-icon layui-icon-edit " data-id="${id}"></i>
              </button>
              <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn_delete"
                style="width: 30px; border-radius: 50%; padding: 0 8px;"  data-id="${id}">
                <i class="layui-icon layui-icon-delete btn_delete" data-id="${id}"></i>
              </button>
            </td>
          </tr>
        `
  }).join('')
  renderimgPage(data)
}
getimgList()

// todo ================下拉框处理=================
axios.get('/ydd_advpos/all').then(({ data: { data } }) => {
  // console.log(data)
  let newArr = data.map((item) => {
    return `<option value="${item.id}">${item.advposname}</option>`
  }).join('')
  document.querySelector('#cateSelect').innerHTML = `<option value="">请选择广告位</option>` + newArr
  form.render('select')
})


// todo  ===============添加广告位弹出框===============
const addimgFormStr = `
       
       <form id="addForm" class="layui-form"  lay-filter="filter">
        <!-- 第一行 广告位 -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告位</label>
          <div class="layui-input-block" style="width: 400px;height: 30px;">          
              <select id="dyncity" name="advimgpos" lay-verify="required">
                <option value="">请选择广告位</option>
              </select>
          </div>
        </div>
        <!-- 第二行 广告图描述  -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告图描述</label>
          <div class="layui-input-block">
            <textarea  id="advimgdesc" name="advimgdesc" placeholder="请输入广告图描述" style="width: 400px;height: 50px;"></textarea>
          </div>
        </div>
        <!-- 第三行 广告图链接  -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告图链接</label>
          <div class="layui-input-block">
            <input type="text" id="advimglink" name="advimglink" required lay-verify="required" placeholder="请输入广告图链接" autocomplete="off"
              style="width: 400px;height: 30px;">
          </div>
        </div>
        <!-- 第四行 广告图  -->
        <div class="layui-form-item">
        <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i style="color: red;text-align:      center;">*</i> 广告图</label>
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal" id="btnChooseCoverImage">点击上传</button>
          <input type="file" style="display: none;" id="upload" accept="image/jpeg,image/png,image/gif,image/bmp">
          <div  id="showimg" style="width:300px;height:50px;display:none">
            <img src=""  id="img" width="100%"/>
          </div>
        </div>
        </div>
              <!-- 第五行 按钮 -->
        <div class="layui-form-item" style="position: relative;">
          <div class="layui-input-block" style="width:200px;position: absolute;right: 10px;bottom: -80px;">
            <button type="reset" class="layui-btn layui-btn-primary closeBtn">取消</button>
            <button class="layui-btn addimgData"  lay-filter="formDemo" lay-submit  style=" background-color: #1e9fff;">确定</button>
          </div>
        </div>
      </form>
`

let indeximgAddForm // 此处index 表示弹出层的索引 

const layer = layui.layer
const form = layui.form
// form.render()
// todo  =================添加功能 显示添加框=================

$('#addimgBtn').on('click', async function (e) {
  e.preventDefault()
  indeximgAddForm = layer.open({
    content: addimgFormStr, // 内容
    type: 1, //页面层
    title: '添加广告图', // 标题
    area: ['800px', '400px'], // 宽高
    // btnAlign: 'r'
  })

  // todo =============获取添加框的下拉栏===========
  const { data: { data } } = await axios.get('/ydd_advpos/all')
  // console.log(data)
  let newData = data.map((item) => {
    return `<option value="${item.id}">${item.advposname}</option>`
  }).join('')

  $('#dyncity').html(`<option value="">请选择广告位</option>` + newData)
  form.render()



  //  todo  ========上传图片功能========
  $('#btnChooseCoverImage').on('click', function () {
    $('#upload').click()
  })
  // 监听文件的上传 
  $('#upload').on('change', async function () {
    let fd
    let file = this.files[0] // 用户选择的文件
    if (!file) {
      return layer.msg('请选择图片!')
    }
    fd = new FormData()
    fd.append('file', file)
    // 上传图片 显示图片 
    let { data } = await axios.post('/common/upload', fd, { params: { "type": "images" } })
    $('#img').attr('src', '') // 先清空上一次的图片
    $('#btnChooseCoverImage').hide()
    $('#showimg').show()
    $('#img').attr('src', "http://124.223.14.236:8060/" + data.data.savePath)
    path = data.data.savePath
  })

  // 关闭图片 显示 上传按钮
  $('#showimg').on('click', function () {
    $('#showimg').hide()
    $('#btnChooseCoverImage').show()
  })

  $('.closeBtn').on('click', function () {
    layer.close(indeximgAddForm)
  })


  // todo  ==================添加功能  注册点击事件给表单==================
  let path
  $('body').on('submit', '#addForm', async function (e) {
    e.preventDefault()

    const basedata = $(this).serialize()

    const finaldata = basedata + '&advimgsrc=' + path
    // console.log(finaldata)
    const { data } = await axios.post('/ydd_advimg/add', finaldata)
    if (data.errno !== 0) {
      return layer.msg('添加广告图失败！')
    }
    layer.msg('添加广告图成功！')
    layer.close(indeximgAddForm)
    getimgList()
  })


})




// todo  ===============修改广告位弹出框===============
const editimgFormStr = `
       
       <form id="editForm" class="layui-form"  lay-filter="filter">
        <!-- id 隐藏框 -->        
         <div class="layui-form-item layui-hide">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i style="color: red;text-align: center;">*</i> 广告位编号</label>
          <div class="layui-input-block">
           <input type="text" name="id" required lay-verify="required"  style="width: 400px;height:30px;">
          </div>
        </div>
        <!-- 第一行 广告位 -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告位</label>
          <div class="layui-input-block" style="width: 400px;height: 30px;">          
              <select id="editDyncity" name="advimgpos" lay-verify="required">
                <option value="">请选择广告位</option>
              </select>
          </div>
        </div>
        <!-- 第二行 广告图描述  -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告图描述</label>
          <div class="layui-input-block">
            <textarea name="advimgdesc" placeholder="请输入广告图描述" style="width: 400px;height: 50px;"></textarea>
          </div>
        </div>
        <!-- 第三行 广告图链接  -->
        <div class="layui-form-item">
          <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i
              style="color: red;text-align: center;">*</i> 广告图链接</label>
          <div class="layui-input-block">
            <input type="text" name="advimglink" required lay-verify="required" placeholder="请输入广告图链接" autocomplete="off"
              style="width: 400px;height: 30px;">
          </div>
        </div>
        <!-- 第四行 广告图  -->
        <div class="layui-form-item">
        <label class="layui-form-label" style="font-size: 14px;font-weight: 700;"><i style="color: red;text-align:      center;">*</i> 广告图</label>
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal" id="btnChooseCoverImage">点击上传</button>
          <input type="file" style="display: none;" id="file" accept="image/jpeg,image/png,image/gif,image/bmp">
          <div  id="showimg" style="width:300px;height:50px;display:none">
            <img src=""  id="img" width="100%"/>
          </div>
        </div>
        </div>
        <!-- 第五行 按钮 -->
        <div class="layui-form-item" style="position: relative;">
          <div class="layui-input-block" style="width:200px;position: absolute;right: 10px;bottom: -80px;">
            <button type="reset" class="layui-btn layui-btn-primary closeimgBtn">取消</button>
            <button class="layui-btn editimgData"  lay-filter="formDemo" lay-submit  style=" background-color: #1e9fff;">确定</button>
          </div>
        </div>
      </form>
`
let indeximgEditForm

// todo ================= 注册点击事件显示修改框==================

$('#list').on('click', '.btn_editImg', function (e) {
  // console.log(111)
  indeximgEditForm = layer.open({
    content: editimgFormStr, // 内容
    type: 1, //页面层
    title: '修改广告图', // 标题
    area: ['650px', '500px'], // 宽高
  })

  // todo  ==========广告位下拉框处理===============
  axios.get('/ydd_advpos/all').then(({ data: { data } }) => {
    // console.log(data)
    let newData = data.map((item) => {
      return `<option value="${item.id}">${item.advposname}</option>`
    }).join('')
    $('#editDyncity').html(`<option value="">请选择广告位</option>` + newData)
    form.render()
  })

  // todo  ===============图片处理=================


  // 点击显示文件框
  $('#btnChooseCoverImage').on('click', function () {
    $('#file').click()
  })
  // 监听文件的上传 
  $('#file').on('change', async function () {
    let fd
    let file = this.files[0] // 用户选择的文件
    if (!file) {
      return layer.msg('请选择图片!')
    }
    fd = new FormData()
    fd.append('file', file)
    // 上传图片 显示图片 
    let { data } = await axios.post('/common/upload', fd, { params: { "type": "images" } })
    $('#img').attr('src', '') // 先清空上一次的图片
    $('#btnChooseCoverImage').hide()
    $('#showimg').show()
    $('#img').attr('src', "http://124.223.14.236:8060/" + data.data.savePath)
    path = data.data.savePath
  })

  // 关闭图片 显示 上传按钮
  $('#showimg').on('click', function () {
    $('#showimg').hide()
    $('#btnChooseCoverImage').show()
  })

  //点击取消关闭弹出框
  $('.closeimgBtn').on('click', function () {
    layer.close(indeximgEditForm)
  })

  // todo  ==================回显数据==================

  const id = $(this).data('id')
  // console.log(id)

  axios.get('/ydd_advimg/rowInfo', { params: { id } }).then(res => {
    // console.log(res)

    $('#showimg').show()
    $('#showimg img').attr('src', "http://124.223.14.236:8060/" + res.data.data.advimgsrc)

    form.val('filter', res.data.data)

  })
})



// todo  ===========上传修改信息 ======================
$('body').on('submit', '#editForm', async function (e) {

  e.preventDefault()
  // console.log(e.target)

  const fd2 = new FormData(e.target)
  // console.log(fd2)
  const files = document.querySelector('#file').files[0]
  // console.log(files)
  if (files) {
    const fd = new FormData()
    fd.append('file', files)
    // console.log(fd)
    const { data: { data: { savePath } } } = await axios.post('/common/upload?type=images', fd, {
      headers: { 'Content-Type': false }
    })
    // console.log(res)
    fd2.append('advimgsrc', savePath)
  }

  const res = await axios.post('/ydd_advimg/update', fd2)
  console.log(res)
  if (res.data.errno !== 0) {
    return layer.msg('修改失败')
  }
  // 新增成功后 关闭弹出层 因为此弹出层（layer.open） 有索引 所以得配合上面进行删除
  layer.close(indeximgEditForm)

  // 渲染数据
  getimgList()

  // 添加成功后弹出提示
  layer.msg('修改成功')

})



// todo  ==================删除功能==================

document.querySelector('#list').addEventListener('click', async function (e) {

  if (e.target.classList.contains('btn_delete')) {
    // console.log(111)
    const id = e.target.dataset.id
    // console.log(id)
    const { data } = await axios.get(`/ydd_advimg/del?id=${id}`)
    // console.log(data)
    if (data.errno !== 0) return layer.msg(data.errmsg, { icon: 6 })

    getimgList()
    layer.msg('删除成功', { icon: 6 })

    if (document.querySelector('.btn_delete').length === 1) {
      if (query.page === 1) {
        query.page = 1
      } else {
        query.page = query.page - 1
      }
    }
  }
})

// todo 分页功能
const laypage = layui.laypage

function renderimgPage(data) {
  // 完整显示
  laypage.render({
    elem: 'pageboxImg', // 元素 id
    count: data.count, // 数据总数
    curr: data.currentPage, //当前第几页（会决定第几个按钮高亮）
    limit: data.pageSize,//每页显示的条数
    limits: [10, 20, 40, 50, 100],//下拉框每一项的结果
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], // 功能布局
    theme: '#409eff',
    jump: function (obj, first) {
      // console.log(obj.curr, obj.limit)

      query.page = String(obj.curr)
      query.limit = String(obj.limit)
      // console.log('first的值', first)

      if (!first) {
        getimgList()
      }
    }
  })
}


// todo  ==================搜索功能==================
const advimgdescObj = document.querySelector('.searchAdvname')
const selectObj = document.querySelector('#cateSelect')
document.querySelector('#search').addEventListener('click', function (e) {
  e.preventDefault()
  query.advimgdesc = advimgdescObj.value
  query.advimgpos = selectObj.value
  getimgList()
})

// todo ==================重置功能==================
document.querySelector('#chongzhi').addEventListener('click', function () {
  query.page = 1,
    query.limit = 10,
    query.advimgdesc = '',
    query.advposname = ''

  layer.msg('重置成功')
  document.querySelector('.searchAdvname').value = ''
  document.querySelector('#cateSelect').value = ''
  getimgList()
})


// todo  ==================右侧按钮区==================
// 设置开关
let flagOpen = true

$('.guanbi_2').on('click', function (e) {
  e.preventDefault()
  if (flagOpen) {
    $('.one_1').show().siblings().hide()
    $('#sousuoLan_2').hide()
    flagOpen = !flagOpen
  } else {
    $('.one_2').show().siblings().hide()
    $('#sousuoLan_2').show()
    flagOpen = !flagOpen
  }
})

document.querySelector('.shuaxin2').addEventListener('click', function (e) {

  e.preventDefault()
  query.advimgdesc = '', // 广告图描述
    query.advimgpos = '', // 广告图所在广告位id
    // console.log(11)
    getimgList()
})



$('.shanchu').on('click', function (e) {
  e.preventDefault()

})

// todo  ===============复选框问题 ===================


$('body').on('click', '.checkall', function () {
  // console.log(111) 
  const checked = $(this).prop('checked')
  $('.j-checkbox,.checkall').prop('checked', checked)
})
$('body').on('click', '.j-checkbox', function () {
  $('.checkall').prop('checked', $('.j-checkbox').length === $('.j-checkbox:checked').length)
})